package httpCall

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
)

//第二参数传，需要解析的类型变量地址
func GetRequestParams(r *http.Request, fBody interface{}) error {
	if r == nil || fBody == nil {
		return errors.New("Request or fBody is nil")
	}
	if ct := r.Header.Get("content-type"); ct != "application/json" {
		//return errors.New("contentType:" + ct + ",won't support it.")
		return fmt.Errorf("Unsupported contentType:%s", ct)
	}

	return FormatRequestBody(r, fBody)
}

//解析http.Request里面的body
//可以解析map或者结构体，第二参数传，需要解析的类型变量地址
func FormatRequestBody(r *http.Request, fBody interface{}) error {
	if r == nil || fBody == nil {
		return errors.New("Request or fBody is nil")
	}
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return err
	}

	if err = json.Unmarshal(body, fBody); err != nil {
		return err
	}
	return nil
}

func test() {
	parData := make(map[string]interface{})
	//仅支持这种方式
	err := GetRequestParams(nil, &parData)

	fmt.Println(parData, err)
}
